<template>
  <div class="tongbu">
    <!--  卡业务明细-同步卡报表 -->
    <el-table
      v-loading="loading"
      :data="detailslist"
      ref="table"
      border
      highlight-current-row
      :header-cell-style="headFirst"
      style="width: 100%"
      :cell-style="
        detailsTotal ? (res) => headFirst_col(res, detailslist) : () => {}
      "
    >
      <el-table-column
        prop="cardNumber"
        label="卡号"
        v-if="formThead.cardNumber.checked"
      >
      </el-table-column>
      <el-table-column
        prop="userName"
        label="姓名"
        v-if="formThead.userName.checked"
      >
      </el-table-column>
      <el-table-column
        prop="departmentName"
        label="部门"
        v-if="formThead.departmentName.checked"
      >
      </el-table-column>
      <el-table-column prop="walletName" label="钱包名称" v-if="formThead.walletName.checked"></el-table-column>
      <el-table-column
        prop="oldBalance"
        label="原主钱包金额(元)"
        v-if="formThead.oldBalance.checked"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.oldBalance | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="newBalance"
        label="同步后主钱包金额(元)"
        v-if="formThead.newBalance.checked"
      >
        <template slot-scope="scope">
          <div>{{ scope.row.newBalance | amountyuan }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="syncTime"
        label="操作时间"
        v-if="formThead.syncTime.checked"
        min-width="120"
      >
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChangepage"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="recordCount"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import bus from "@/bus.js";
export default {
  data() {
    return {
      pageNum: 1,
      pageSize: 20,
      currentPage: 0,
      recordCount: 0,
      searchInfo: {},
      loading: false,
      filename: "同步卡明细表",
      detailsTotal: null,

      detailslist: [],
      formThead: {
        cardNumber: { label: "卡号", prop: "cardNumber", checked: true },
        userName: { label: "姓名", prop: "userName", checked: true },
        departmentName: {
          label: "部门",
          prop: "departmentName",
          checked: true,
        },
        walletName: { label: '钱包名称', prop: 'walletName', checked: true },
        oldBalance: {
          label: "原主钱包金额(元)",
          prop: "oldBalance",
          checked: true,
        },
        newBalance: {
          label: "同步后主钱包金额(元)",
          prop: "newBalance",
          checked: true,
        },
        syncTime: { label: "操作时间", prop: "syncTime", checked: true },
      },
      detailslistExportlist: [],
    };
  },
  mounted() {
    bus.$on("listenToA", this.getHeaderDate);
    // bus.$on('onsumbit',this.getsearchInfodata)
  },
  watch: {},
  props: ["userName", "departmentGuid", "datetime", "unitGuid",
  
    'waterWalletNo'
  ],
  methods: {
    // 自定义字段
    getHeaderDate(val) {
       this.$nextTick(() => {
        this.$refs["table"].doLayout();
      });
      this.formThead = val;
    },
    // 查询同步报表
    async getsearchInfodata() {
      this.pageNum = 1;
      this.searchInfo = {};
      if (this.userName !== null && this.userName !== "") {
        this.searchInfo.userName = this.userName;
      }
      if (this.departmentGuid !== null && this.departmentGuid !== "") {
        this.searchInfo.departmentGuid = this.departmentGuid;
      }
      if (this.datetime !== null && this.datetime !== "") {
        this.searchInfo.startTime = this.datetime[0];
        this.searchInfo.endTime = this.datetime[1];
      }
      this.searchInfo.walletNo = this.waterWalletNo
      this.searchInfo.unitGuid = this.unitGuid;
      this.detailsTotal = null;
      this.detailsTotal = await this.getTotal();
      this.getreportsync();
    },
    // 获取同步报表合计数据
    getTotal() {
      let _this = this;
      _this.loading = true;
      return new Promise(function (resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl("/card/report/sync-total"),
            method: "post",
            data: _this.$http.adornData({
              messageContent: _this.searchInfo,
              messageType: 0,
            }),
          })
          .then(({ data }) => {
            _this.loading = false;
            if (data.messageCode == 200) {
              resolve(data.messageContent);
            } else {
              reject(data.errorMessage);
              this.$message.error(data.errorMessage);
            }
          });
      });
    },
    //获取同步报表
    getreportsync() {
      this.loading = true;
      this.$http({
        url: this.$http.adornUrl("/card/report/sync"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        this.loading = false;
        if (data.messageCode == 200) {
          console.log(data);
          this.detailslist = data.messageContent.data;
          this.recordCount = data.messageContent.recordCount;
          this.currentPage = data.messageContent.pageNum;
           if (data.messageContent.data.length == 0) {
            this.$message({
              message: "查询成功当前暂无数据",
              type: "success",
            });
          }
          if (data.messageContent.data.length != 0) {
            this.detailslist.push({ ...this.detailsTotal });
          }
        } else {
          this.$message.error(data.errorMessage);
        }
      });
    },
    async exportlist(type) {
      if (this.detailslist.length == 0) {
        this.$message({
          message: "请查询数据后,在进行此操作",
          type: "warning",
        });
        return false;
      }
      await this.outexecel();
      if (type == "print") {
        this.printJS();
      } else {
        this.export2Excel();
      }
    },
    // 拿到表头数据
    getIsPrint() {
      // const filterValArr = [
      //   "cardNumber",
      //   "userName",
      //   "departmentName",
      //   "oldBalance",
      //   "newBalance",
      //   "syncTime",
      // ];
      const filterValArr = Object.keys(this.formThead)
      let valArr = [];
      let tHeader = [];
      filterValArr.map((item) => {
        if (this.formThead[item].checked) {
          valArr.push(this.formThead[item].prop);
          tHeader.push(this.formThead[item].label);
        }
      });
      return { filterValArr: valArr, tHeader };
    },
    // 打印
    printJS() {
      let someJSONdata = this.detailslistExportlist;
      const title = "同步卡明细表";
      this.unitName = sessionStorage.getItem("unitName");
      const properties = [];
      // 拿到数据,filterValArr为数据值，tHeader为数据标题，一一对应
      const { filterValArr, tHeader } = this.getIsPrint();
       filterValArr.map((item, index) => {
        if (filterValArr[index] == "syncTime") {
          properties.push({
            displayName: tHeader[index],
            field: filterValArr[index],
            columnSize: 130 / (Object.keys(this.formThead).length + 1) + "%",
          });
        } else {
          properties.push({
            displayName: tHeader[index],
            field: filterValArr[index],
            columnSize: 100 / (Object.keys(this.formThead).length + 1) + "%",
          });
        }
      });
    
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(
          title,
          this.unitName,
          `${this.formatDate(
            new Date(this.searchInfo.startTime),
            "yyyy-MM-dd"
          )} 至 ${this.formatDate(
            new Date(this.searchInfo.endTime),
            "yyyy-MM-dd"
          )}`
        ),
        printable: someJSONdata,
        properties: properties,
        type: "json",
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem("username"),
          this.getNowTime("yy-mm-dd hh:mm:ss")
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle(),
      });
    },
    // 获取导出数据
    outexecel() {
      let _this = this;
      return new Promise(function (resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl("/card/report/sync"),
            method: "post",
            data: _this.$http.adornData({
              messageContent: {
                pageNum: 1,
                pageSize: _this.recordCount,
                searchInfo: _this.searchInfo,
              },
              messageType: _this.messageType,
            }),
          })
          .then(({ data }) => {
            if (data.messageCode === 200) {
              _this.detailslistExportlist = data.messageContent.data;
              if (data.messageContent.data.length != 0) {
                _this.detailslistExportlist.push({ ..._this.detailsTotal });
              }
              for (var i = 0; i < _this.detailslistExportlist.length; i++) {
                _this.detailslistExportlist[i].newBalance = _this.amountyua(
                  _this.detailslistExportlist[i].newBalance
                );
                _this.detailslistExportlist[i].oldBalance = _this.amountyua(
                  _this.detailslistExportlist[i].oldBalance
                );
              }
              // setTimeout(() => {
              //   _this.export2Excel();
              // }, 100);
              resolve(_this.detailslistExportlist);
            } else {
              reject(data.errorMessage);
              _this.$message.error(data.errorMessage);
            }
          });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    export2Excel() {
      const nowtime = this.getimeto();
      require.ensure([], () => {
        const { export_json_to_excel } = require("../../excel/Export2Excel");
        const multiHeader = [];
        const multiHeader2 = [];
        const merges = [];
        let tHeaderarr = [];
        const { tHeader, filterValArr } = this.getIsPrint()
        const filterVal = filterValArr
        const list = this.detailslistExportlist;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime,
        });
      });
    },
    getreportsynciniit(val) {
      //  console.log(val)
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.getreportsync();
    },
    handleCurrentChangepage(val) {
      this.pageNum = val;
      this.getreportsync();
    },
  },
};
</script>

<style lang="scss" scoped>
.tongbu {
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }
}

.page {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>